package com.llb666.shop.items.domain.service;

import com.llb666.common.core.utils.page.PagedGridResult;
import com.llb666.shop.items.api.vo.SearchItemsVo;
import com.llb666.shop.items.domain.entity.es.EsItems;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 商城商品信息查询---根据es中文分词查询.
 *
 * @author llb666
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ItemsEsService {

    private final ElasticsearchRestTemplate esTemplate;

    public PagedGridResult<SearchItemsVo> highlightSearchItems(String keywords, String sort, Integer page, Integer pageSize) {
        // 构建排序.
        FieldSortBuilder sortBuilder = null;
        if (sort.equals("c")) {
            sortBuilder = new FieldSortBuilder("sellCounts").order(SortOrder.DESC);
        } else if (sort.equals("p")) {
            sortBuilder = new FieldSortBuilder("price").order(SortOrder.ASC);
        } else {
            //注意  mapping中 itemName 属性需要设置 fielddata = true
            sortBuilder = new FieldSortBuilder("itemName").order(SortOrder.ASC);
        }
        // 相关性查询扩展.
        Integer catRootId = null;
        //  遍历  categoryWorkMap
        for (Integer key : categoryWorkMap.keySet()) {
            List<String> list = categoryWorkMap.get(key);
            if (list.contains(keywords)) {
                catRootId = key;
            }
        }
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (catRootId != null) {
            boolQueryBuilder.must(QueryBuilders.termQuery("rootCatId",catRootId));
        }
        String itemNameFiled = "itemName";
        boolQueryBuilder.must(QueryBuilders.matchQuery(itemNameFiled, keywords));

//        HighlightQuery highlightQuery = new HighlightQuery
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                // 排序
                .withSorts(sortBuilder)
                .withQuery(boolQueryBuilder)
//                .withQuery(QueryBuilders.prefixQuery(itemNameFiled, keywords).boost(0.2f))
                .withPageable(PageRequest.of(page, pageSize))
                .withHighlightFields(new HighlightBuilder.Field(itemNameFiled))
                .withHighlightBuilder(new HighlightBuilder().preTags("<font color='red'>").postTags("</font>"))
                .build();
        log.info(Objects.requireNonNull(searchQuery.getQuery()).toString());
        // 查询
        SearchHits<EsItems> search = esTemplate.search(searchQuery, EsItems.class);
        // 得到查询返回的内容
        List<SearchHit<EsItems>> searchHits = search.getSearchHits();
        // 设置一个最后需要返回的实体类集合
        List<SearchItemsVo> searchItemsVoList = new ArrayList<>();
        // 遍历返回的内容进行处理
        for (SearchHit<EsItems> searchHit : searchHits) {
            // 高亮的内容
            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
            // 将高亮的内容填充到content中
            searchHit.getContent().setItemName(highlightFields.get(itemNameFiled) == null
                    ? searchHit.getContent().getItemName() : highlightFields.get(itemNameFiled).get(0));
            EsItems esItems = searchHit.getContent();
            SearchItemsVo searchItemsVo = SearchItemsVo.Converter.INSTANCE.do2Vo(esItems);
            // 放到实体类中
            searchItemsVoList.add(searchItemsVo);
        }
        PagedGridResult<SearchItemsVo> gridResult = new PagedGridResult<>();
        gridResult.setRows(searchItemsVoList);
        gridResult.setPage(page + 1);
        gridResult.setTotal(searchItemsVoList.size());
        gridResult.setRecords(search.getTotalHits());
        return gridResult;
    }

    private final Map<Integer, List<String>> categoryWorkMap = new HashMap<>();

    @PostConstruct
    public void init() {
        categoryWorkMap.put(1, new ArrayList<>());

        categoryWorkMap.get(1).add("iphone");
    }

}
